package com.mianyang.zhangsan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mianyang.zhangsan.common.util.OperationManHelper;
import com.mianyang.zhangsan.common.util.StringUtils;
import com.mianyang.zhangsan.model.dto.SecApprovalDto;
import com.mianyang.zhangsan.model.entity.SecApproval;
import com.mianyang.zhangsan.mapper.SecApprovalMapper;
import com.mianyang.zhangsan.plugin.approval.ApprovalAdaptor;
import com.mianyang.zhangsan.service.ISecApprovalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 审批服务
 * @author jiangjr
 * @since 2022-10-23
 */
@Service
public class SecApprovalServiceImpl extends ServiceImpl<SecApprovalMapper, SecApproval> implements ISecApprovalService {
    @Autowired
    private ApprovalAdaptor approvalAdaptor;


    @Override
    public List<SecApproval> selectSelfApply(Long userId) {
        QueryWrapper<SecApproval> wrapper = new QueryWrapper<>();
        if (userId != null) {
            wrapper.eq("sender_id", userId);
            return list(wrapper);
        }
        return null;
    }

    @Override
    public Page<SecApproval> selectSelfApproval(String senderName, Integer approvalStatus, Integer current, Integer pageSize) {
        QueryWrapper<SecApproval> wrapper = new QueryWrapper<>();
        Long accountId = OperationManHelper.getAccountId();
        if (accountId == null) {
            return null;
        }
        wrapper.eq("receive_id", accountId);
        if (StringUtils.isNotEmpty(senderName)) {
            wrapper.like("sender_name", senderName);
        }
        if (approvalStatus != null) {
            wrapper.eq("approval_status", approvalStatus);
        }
        return page(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public void deleteSelfApproval(Long approvalId) {
        removeById(approvalId);
    }

    @Override
    public void updateApproval(SecApprovalDto approval) {
        // 更新审批结果
        updateById(approval.getApproval());
        // 处理审批
        approvalAdaptor.adaptor(approval.getType(), approval);
    }

    @Override
    public void sendApply(SecApprovalDto approval) {
        // 保存审批内容
        save(approval.getApproval());
        // todo 向审批人发起通知
    }
}
